/*
 * $Id: MockGeneratorMojo.java,v 1.5 2011/02/24 09:13:15 tvyletel Exp $
 * Created on 21.2.2011, 11:08:12
 */

package com.tivyso.testing.mock.generator;

import java.util.List;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import com.tivyso.testing.mock.generator.componentfilter.ClassNameComponentFilter;

/**
 * @author tv
 * 
 * @goal generate-mocks
 */
public class MockGeneratorMojo extends AbstractMojo {

	/**
	 * Target directory for generated classes
	 * 
	 * @parameter expression="${directory}"
	 *            default-value="${project.build.directory/generated-classes}"
	 */
	private String directory;

	/**
	 * Target directory for generated classes
	 * 
	 * @parameter
	 */
	private String basePackage;

	/**
	 * Class to be ignored during generation (comma separated, do not include the 'basePackage' part
	 * (added automatically))
	 * 
	 * @parameter
	 */
	private List excludes;

	public void execute() throws MojoExecutionException, MojoFailureException {

		MockGenerator generator = new MockGenerator();
		generator.setOutputDir(directory);
		generator.setBasePackage(basePackage);
		generator.setMockedPackageNameCreator(new MockSuffixPackageNameCreator(basePackage));
		addFilters(generator);
		try {
			generator.loadComponents();
			generator.generate();
			generator.generateMockedModelFactory();
		} catch (IllegalAccessException iae) {
			throw new MojoExecutionException("Mock generation failed!", iae);
		}
	}

	private void addFilters(MockGenerator generator) {
		if (excludes == null) {
			return;
		}

		String fullName = null;

		for (Object i : excludes) {
			fullName = basePackage + "." + i;
			getLog().info("Adding exclude filter for: " + fullName);
			generator.addComponentExcludeFilter(new ClassNameComponentFilter(fullName));
		}
	}
}

class MockSuffixPackageNameCreator implements IMockedPackageNameCreator {

	private String base;

	public MockSuffixPackageNameCreator(String basePackage) {
		this.base = basePackage;
	}

	public String createPackageName(String componentPackageName) {
		return "generated_mocks" + componentPackageName.replace(base, "");
	}

}
